﻿using System;
using System.IO;
using System.Text;
using System.Windows.Input;
using RG.Common.WPF.Commands;
using Microsoft.Practices.Unity;
using RG.Common;

namespace RG.Common.WPF.Dialogs
{
    /// <summary>
    /// Interaction logic for UnhandledErroreDlg.xaml
    /// </summary>
    [SupportDataBinding]
    public partial class UnhandledErroreDlg 
    {
        public string ErroreMessage { get; set; }
        public string ErrorBody { get; set; }
        public string Caption { get; set; }
        public IUnityContainer Cfg { get; set; }
        public IWorkplace Workplace { get; set; }
        public StringBuilder HelpData { get; set; }

        public string ScreenPath { get; set; }

        public ICommand OkCmd { get; set; }
        public ICommand CancelCmd { get; set; }
        public ICommand SendErroreCmd { get; set; }

        public UnhandledErroreDlg(IUnityContainer cfg)
        {
            InitializeComponent();
            Cfg = cfg;
            Workplace = Cfg.Resolve<IWorkplace>();
            OkCmd = new DelegateCommand(DoOk);
            CancelCmd = new DelegateCommand(DoCancel);
            SendErroreCmd = new DelegateCommand(DoSendErrore);
            DataContext = this;
        }
       
        private void DoOk()
        {
            DialogResult = true;
            Close();
        }

        private void DoCancel()
        {
            DialogResult = false;
            Close();
        }

        private void DoSendErrore()
        {
            var errorMsg = "";
            var sbj = string.Format("{0} {1}", Environment.MachineName, DateTime.Now);
            var vm = Cfg.Resolve<TextBoxDialogVM>();
            errorMsg = !Workplace.ShowEditableDialog(vm, "Опишите ваши действия до возникновения ошибки:")
                           ? string.Format("Опишите ваши действия до возникновения ошибки {0}", ErrorBody)
                           : string.Format("{0} {1}", vm.Text, ErrorBody);
            var message = new MapiMailMessage(sbj, errorMsg, "ts-request@marya.ru");

            if (!string.IsNullOrEmpty(HelpData.ToString()))
            {
                var tempFileName = string.Format(@"{0}\{1}.txt", Path.GetTempPath(), sbj.FixFileName());
                using (var fs = new FileStream(tempFileName, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (var sr = new StreamWriter(fs))
                    {
                        sr.Write(HelpData.ToString());
                    }
                }
                message.Files.Add(tempFileName);
                if (!string.IsNullOrEmpty(ScreenPath)) message.Files.Add(ScreenPath);
            }
            message.ShowDialog();
        }
    }
}
